using System;
using System.Data;
using System.Text;

using Elev.Core.Data;
using Elev.Core.DBUpdates;
using Elev.Core.Utility;

namespace Elev.Core.DAL
{
    internal class MetaInfoInternal : SqliteTable
    {
        public MetaInfoInternal() { }

        bool KeyExists(string Key)
        {
            string SQL = "SELECT COUNT(*) FROM MetaInfo WHERE Key = @Key;";
            return (Convert.ToInt32(SqliteAdapter.Get().ExecuteScalar(SQL, "@Key", Key)) == 1);
        }

        public object GetValue(string Key)
        {
            if (!KeyExists(Key)) return null;

            string SQL = "SELECT Value FROM MetaInfo WHERE Key = @Key;";
            return SqliteAdapter.Get().ExecuteScalar(SQL, "@Key", Key);
        }

        public void SetValue(string Key, string Value)
        {
            string SQL;
            
            if (!KeyExists(Key))
                SQL = "INSERT INTO MetaInfo (Key, Value) VALUES (@Key, @Value)";
            else
                SQL = "UPDATE MetaInfo SET Value = @Value WHERE Key = @Key";
            
            SqliteAdapter.Get().ExecuteNonQuery(SQL, "@Key", Key, "@Value", Value);
        }

        #region ISqliteTable Members

        public override void Create()
        {
            string SQL = "CREATE TABLE [MetaInfo] (" +
                            " Key VARCHAR NOT NULL," +
                            " Value VARCHAR NOT NULL)";

            SqliteAdapter.Get().ExecuteNonQuery(SQL);

            SQL = "INSERT INTO MetaInfo(Key, Value) Values(@Key, @Value);";
            SqliteAdapter.Get().ExecuteNonQuery(SQL, "@Key", "DBVERSION", "@Value", DBUpdater.DB_VERSION_EXPECTED);
        }

        public override void Drop()
        {
            string SQL = "DROP TABLE [MetaInfo]";
            SqliteAdapter.Get().ExecuteNonQuery(SQL);
        }

        #endregion
    }
}
